import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '首页', icon: 'House' }
      },
      {
        path: 'students',
        name: 'Students',
        component: () => import('@/views/students/StudentList.vue'),
        meta: { title: '学生管理', icon: 'User' }
      },
      {
        path: 'students/:id',
        name: 'StudentDetail',
        component: () => import('@/views/students/StudentDetail.vue'),
        meta: { title: '学生详情', hidden: true }
      },
      {
        path: 'grades',
        name: 'Grades',
        component: () => import('@/views/grades/GradeList.vue'),
        meta: { title: '成绩管理', icon: 'Document' }
      },
      {
        path: 'rewards',
        name: 'Rewards',
        component: () => import('@/views/rewards/RewardList.vue'),
        meta: { title: '奖励管理', icon: 'Trophy' }
      },
      {
        path: 'punishments',
        name: 'Punishments',
        component: () => import('@/views/punishments/PunishmentList.vue'),
        meta: { title: '惩罚管理', icon: 'Warning' }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/users/UserList.vue'),
        meta: { title: '用户管理', icon: 'Setting', requiresAdmin: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { title: '404' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  document.title = to.meta.title 
    ? `${to.meta.title} - 学生信息管理系统` 
    : '学生信息管理系统'
  
  // 检查是否需要登录
  if (to.meta.requiresAuth !== false) {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      next('/login')
      return
    }
    
    // 检查是否需要管理员权限
    if (to.meta.requiresAdmin && userStore.userRole !== 'admin') {
      ElMessage.error('没有权限访问该页面')
      next('/')
      return
    }
  } else if (to.path === '/login' && userStore.isLoggedIn) {
    // 已登录用户访问登录页，重定向到首页
    next('/')
    return
  }
  
  next()
})

export default router

